#include "push_init.h"

extern void (*ori_execute_ex)(zend_op_array *op_array TSRMLS_DC);
extern void (*ori_execute_internal)(zend_execute_data *execute_data_ptr, int return_value_used TSRMLS_DC);

extern client *client::instance;

client *pushgateway_client;

void init_minit()
{
    // 初始化客户端实例
    pushgateway_client = client::newInstance();

    // 监控自定义类方法
    ori_execute_ex = zend_execute;
    zend_execute = push_execute_ex;

    // // 监控内置类方法
    ori_execute_internal = zend_execute_internal;
    zend_execute_internal = push_execute_internal;
}

void init_rinit()
{
    int internal = PUSHGATEWAY_G(interval);
    pushgateway_client = client::newInstance();
    pushgateway_client->run(internal);
}

void init_mshutdown()
{
    pushgateway_client = client::newInstance();
    pushgateway_client->syncSend();
}

void init_rshutdown()
{
    if (PUSHGATEWAY_G(debug))
    {
        pushgateway_client = client::newInstance();
        pushgateway_client->debug = true;
        pushgateway_client->output = PUSHGATEWAY_G(output);
    }
}

// 获取请求参数
string server_param(string name)
{
    char *namec = const_cast<char *>(name.c_str());
    int namec_len = name.length() + 1;
    zval **server, **param;

    zend_bool jit_initialization = PG(auto_globals_jit);

    if (jit_initialization)
    {
        zend_is_auto_global("_SERVER", sizeof("_SERVER") - 1 TSRMLS_CC);
    }

    zend_hash_find(&EG(symbol_table), "_SERVER", sizeof("_SERVER"), (void **)&server);
    zend_hash_find(Z_ARRVAL_PP(server), namec, namec_len, (void **)&param);

    string res = param == nullptr ? "" : Z_STRVAL_PP(param);

    return res;
}